package org.onion.pattern.kit.administdivision;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.InputStream;
import java.util.*;

public final class Cities {

    static final Map<String, String> codeAndName = new HashMap<>();
    static final Map<String, Set<String>> provinceCodeAndCityCodeSet = new HashMap<>();

    static {
        InputStream resourceAsStream = Areas.class.getResourceAsStream("/administrative-divisions/cities.json");
        byte[] bytes = IoUtil.readBytes(resourceAsStream);
        JSONArray jsonArray = JSONUtil.parseArray(bytes);
        for (Object node : jsonArray) {
            JSONObject object = (JSONObject) node;
            String name = object.getStr("name");
            String code = object.getStr("code")+"00";
            String provinceCode = object.getStr("provinceCode") + "0000";
            codeAndName.put(code, name);
            Set<String> cityCode = provinceCodeAndCityCodeSet.computeIfAbsent(provinceCode, k -> new HashSet<>());
            cityCode.add(code);

        }
    }

    public static Optional<String> findNameByCode(String code) {
        String name = codeAndName.get(code.trim());
        return Optional.ofNullable(name);
    }

    public static Set<String> findCodeByProvinceCode(String provinceCode) {
        return provinceCodeAndCityCodeSet.getOrDefault(provinceCode, Collections.emptySet());
    }


}
